import axios from 'axios'
import {Message} from 'element-ui'
import router from './router/index'

axios.interceptors.request.use(config => {
  // eslint-disable-next-line
  let expireTime = 1000 * 60 * 30
  let url = config.url
  console.log('handler request url:' + url)
  // Message.error(config.js.toString())
  if (!url.endsWith('/login')) {
    let token = localStorage.getItem('token')
    if (token) {
      // if (expireTime < new Date().getTime() - localStorage.loginTime) {
      //   Message.error('登录超时，请重新登录')
      //   router.push({path: '/login'})
      //   return
      // }
      config.headers.Authorization = token
    } else {
      Message.error('请先登录')
      return
    }
  }
  return config
}, error => {
  console.log(error)
})
// Add a response interceptor
axios.interceptors.response.use(response => {
  // Do something with response data
  console.log('Global interceptor on response: %o', response)
  return response
}, function (error) {
  // Do something with response error
  console.log('onRejected:%o', error)
  if (error.response === undefined) {
    error.message = '网络错误，服务器无响应'
  } else {
    checkTokenStatus(error)
  }
  return Promise.reject(error)
})

function checkTokenStatus (error) {
  if (error.response) {
    let data = error.response
    if (data.status === 401) {
      Message.error(data.data.msg)
      gotoLgin()
    } else if (data.status === 404) {
      Message.error('出错了！' + data.data.msg)
      if (data.data.code === 401) {
        gotoLgin()
      }
    } else if (data.status === 400) {
      Message.error('出错了' + data.data.msg)
    }
  }
}

function gotoLgin () {
  router.push({path: '/login'})
}
